<template>
  <div class="knowledge-base-container">
    <div 
      class="upload-area"
      @dragover.prevent="dragOver"
      @dragleave.prevent="dragLeave"
      @drop.prevent="handleDrop"
      :class="{ 'drag-active': isDragOver }"
    >
      <div v-if="uploadedFiles.length <= 0" class="upload-content">
        <upload-icon class="upload-icon" />
        <p>将图片拖到此处，或<button @click="triggerFileInput">点击上传</button></p>
        <p class="file-types">支持格式: png, jpg, jpeg</p>
      </div>
      <!-- 文件列表 -->
     <!-- 显示已上传文件列表 -->
    <div class="file-list" v-else>
      <div v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
        <div></div>
        <img class="file-img" :src="file.url" alt="" @click="openPhoto(file.url)">
        <el-button class="removeBtn" type="delBtn2" @click="removeFile(index)">删除</el-button>
      </div>
    </div>
      <!-- 隐藏的上传组件 -->
  <el-upload
    ref="uploadRef"
    :file-list="fileList"
    :action="uploadFileUrl"
    method="post"
    :headers="headers"
    :on-success="success"
    :on-remove="handleRemove"
    :before-upload="upload"
     accept=".png,.jpg,.jpeg,"
    :auto-upload="true" 
    :show-file-list="false"  
    style="display: none"  
  >
  </el-upload>
    </div> 
    <!-- 图片线上地址预览 -->
    <div v-if="showPreview" class="preview-modal" @click.self="closePreview">
      <div class="preview-content">
        <img :src="currentImage" class="preview-image" />
        <button class="close-button" @click="closePreview">
          <svg viewBox="0 0 24 24" width="24" height="24">
            <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,onMounted,defineEmits,defineProps } from 'vue';
import UploadIcon from './UploadIcon.vue';
import { ElMessage,ElMessageBox } from 'element-plus'
import { checkPermi } from '@/utils/permission.js'
import { getToken } from '@/utils/auth'
const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 10,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => [''],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  // 回显图片
  urlShow: {
    type: String,
    default: '',
  },
})
const emit = defineEmits(['size'])

// 图片上传
const fileList = ref([]);
const uploadedFiles = ref([]); // 用于存储已上传的文件信息
const isDragOver = ref(false);
const fileInput = ref(null);
const isUploading = ref(false);
const uploadProgress = ref(0);
const uploadComplete = ref(false);


const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadFileUrl = ref(baseUrl + '/common/upload') // 上传文件服务器地址
const headers = { Authorization: 'Bearer ' + getToken() }

const uploadRef = ref(null);
const triggerFileInput = () => {
  uploadRef.value?.$el.querySelector('input[type="file"]').click();
};


const upload = (file) => {
  console.log('上传前处理', file);
  //参数是上传的图片文件
  var index = file.name.lastIndexOf("."); //用于返回指定字符串在当前字符串中最后一次出现的位置。
  var name = file.name.slice(index); //目的用来截取.jpg等字段
  
};
const success = (response,file) => {
  let url = response.url.replace('://erp.urldng.com:33000/', '://erp.urldng.com:33000/prod-api/');
  uploadedFiles.value.push({
        url: url, // 假设后端返回文件URL
        // name: file.name,
        // uid: file.uid
      });
  emit('update:modelValue',url)
};

const handleRemove = (file) => {
  console.log('文件移除', file);
};
// const handleFileSelect = async(e) => {
//   const files = Array.from(e.target.files);
//   console.log(files,'打印上传的文件files');
//   addFiles(files);
//   e.target.value = ''; // 重置input，允许重复选择相同文件
// };

const handleDrop = (e) => {
  dragLeave();
  const files = Array.from(e.dataTransfer.files);
  // addFiles(files);
};

const dragOver = () => {
  isDragOver.value = true;
};

const dragLeave = () => {
  isDragOver.value = false;
};


const removeFile = (index) => {
  uploadedFiles.value.splice(index, 1);
};


const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

const uploadFiles = async () => {
  if (uploadedFiles.value.length === 0) {
    alert('请先上传文件');
    return;
  }
  
  isUploading.value = true;
  uploadComplete.value = false;
  
  // 模拟上传进度
  const interval = setInterval(() => {
    uploadProgress.value += Math.floor(Math.random() * 10) + 5;
    if (uploadProgress.value >= 100) {
      clearInterval(interval);
      setTimeout(() => {
        isUploading.value = false;
        uploadComplete.value = true;
        uploadProgress.value = 0;
        // 实际项目中这里可以调用API进行文件上传
        console.log('上传的文件:', uploadedFiles.value);
      }, 500);
    }
  }, 300);
};

//删除
const privateDetele = (val)=>{
    let {i , v} = val
    console.log(val);
    
    ElMessageBox.confirm(
    '确定要删除该文件吗?',
    '删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
        //  uploadedFiles.value.splice(i,1)
       
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf('/') > -1) {
    return name.slice(name.lastIndexOf('/') + 1)
  } else {
    return name
  }
}

//图片预览
const showPreview = ref(false);
const currentImage = ref('');
//打开预览
const openPhoto = (url)=>{
         currentImage.value = url;
         showPreview.value = true;
         document.body.style.overflow = 'hidden'; // 防止背景滚动
}
// 关闭预览
const closePreview = () => {
  showPreview.value = false;
  document.body.style.overflow = '';
};
// 点击ESC键关闭预览
const handleKeyDown = (e) => {
  if (e.key === 'Escape' && showPreview.value) {
    closePreview();
  }
};
// 添加键盘事件监听
window.addEventListener('keydown', handleKeyDown);
onMounted(()=>{
  if(props.urlShow){
     uploadedFiles.value[0] = {url:props.urlShow} //编辑回显图片
  }
})
</script>

<style scoped>
.knowledge-base-container {
  max-width: 1100px;
  margin: 0 auto;
  /* padding: 2rem; */
  font-family: Arial, sans-serif;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 1rem;
}

.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 1rem 1rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 2rem;
}

.upload-area.drag-active {
  border-color: #4CAF50;
  background-color: rgba(76, 175, 80, 0.1);
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-icon {
  width: 48px;
  height: 48px;
  margin-bottom: 1rem;
  color: #666;
}

.upload-area button {
  background: none;
  border: none;
  color: #4CAF50;
  text-decoration: underline;
  cursor: pointer;
  font-size: inherit;
  padding: 0 0.2rem;
}
.removeBtn{
   background-color: red !important;
   color:#fff !important;
   text-decoration: none !important;
   padding: 10px !important;
}

.file-types {
  color: #666;
  font-size: 0.9rem;
  margin-top: 0.5rem;
}

.uploaded-files {
  margin-top: 2rem;
}

.uploaded-files h3 {
  margin-bottom: 1rem;
  color: #333;
}


.progress-container {
  margin-top: 1.5rem;
  background-color: #f1f1f1;
  border-radius: 4px;
  height: 24px;
  position: relative;
}

.progress-bar {
  background-color: #4CAF50;
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s;
}

.progress-container span {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: white;
  font-size: 0.8rem;
  font-weight: bold;
}

.success-message {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: #e8f5e9;
  border-radius: 4px;
  color: #2e7d32;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action {
  display: flex;
}

.file-list {
  margin-top: 20px;
  /* border: 1px solid #eee; */
  padding: 10px;
  border-radius: 4px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.file-item:last-child {
  border-bottom: none;
}
.file-img{
   width: 200px;
   height: 200px;
}

/* 图片预览样式 */
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
  border-radius: 4px;
}

.close-button {
  position: absolute;
  top: -40px;
  right: -40px;
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 24px;
  padding: 10px;
  transition: transform 0.2s;
}

.close-button:hover {
  transform: scale(1.2);
}

@media (max-width: 768px) {
  .close-button {
    top: -50px;
    right: 10px;
  }
}
</style>
